/**
 * page.js
 * This javascript file handles page rendering and events.
 * 
 * @author 		Tobin Bradley
 * @license 	MIT and GPL dual licensed.
 */


/*  Document Ready */
$(document).ready(function() {
    
    // console.log() hack so console.log calls for testing won't cause IE halts
	try { console.log('init console... done'); } catch(e) { console = { log: function() {} } }
	
	// jQuery UI Layout
    $('body').layout({ applyDefaultStyles: false,
        fxName: "slide",
		fxSettings: { duration: 500 },
        north__size: 65,
        south__size: 20,
        west__size:			300,
        east__size:			8,
		closable: false,
		west__closable: true,
        spacing_open: 0,
        west__spacing_open: 5,
		center__onresize:		"middleLayout.resizeAll" 
	});
	middleLayout = $('div.ui-layout-center').layout({ center__paneSelector:	".ui-layout-middle", center__onresize:		"innerLayout.resizeAll"  }); 
	innerLayout = $('div.ui-layout-middle').layout({ 
		center__paneSelector:	".ui-layout-middle-center",
		north__paneSelector: ".ui-layout-middle-north",
		north__size: 35,
		scapcing_open: 0,
		north__spacing_open: 0,
		closable: false
	});
		
    
    // Accordions
    $("#accordion-map").accordion({header: "h3",  collapsible: true, autoHeight: false});
    $('#accordion-data').accordion({header: "h3", collapsible: true, autoHeight: false }).bind("accordionchange", function(event, ui) {
        if (ui.newHeader[0]) processAccordionDataChange(ui.newHeader[0].id);
    });
    
    // Tabs
    $('#left-tabs').tabs();
	
	// Dialogs
	$("#search-dialog").dialog({ width: $("#searchdiv").width(), autoOpen: false, show: 'bounce', hide: 'fade' });
    
    // Sliders
    $('#opacitySlider').slider({range: "min", min: .1, max: 1, step: .05, value: .5, slide: function(event, ui) {
            map.layers[$('#opacitydll').val()].setOpacity(ui.value);
            $("#layerOpacity").html("Layer Opacity: " + parseInt(ui.value * 100 ) + "%");
        }
    });
	
	// Map Control Buttons
	$("#mapcontrols").buttonset();
	$("#zoomin").button({ icons: { primary: 'ui-icon-circle-zoomin' }, text: false });
	$("#zoomout").button({ icons: { primary: 'ui-icon-circle-zoomout' }, text: false });
	$("#identify").button({ icons: { primary: 'ui-icon-flag' }, text: false });
	$("#zoom_previous").button({ icons: { primary: 'ui-icon-arrowthickstop-1-w' }, text: false });
	$("#zoom_next").button({ icons: { primary: 'ui-icon-arrowthickstop-1-e' }, text: false });
	$("#mapcontrols input:radio").click( function() { toggleControl($(this)) });
	$("#zoom_previous").click( function() { nav.previousTrigger() });
	$("#zoom_next").click( function() { nav.nextTrigger() });
	
	
	// Autocomplete
	$("#searchinput").autocomplete({
		minLength: 4,
		delay: 400,
		source: function(request, response) {
			
			$.ajax({
				url: wsbase + "v2/ws_geo_ubersearch.php",
				dataType: "jsonp",
				data: {
					searchtypes: "Address,Library,School,Park,GeoName,Road,CATS,Intersection,PID",
					query: request.term
				},
				success: function(data) {
					if (data.total_rows > 0) {
						response($.map(data.rows, function(item) {
							return {
								label: urldecode(item.row.displaytext),
								value: item.row.displaytext,
								responsetype: item.row.responsetype,
								responsetable: item.row.responsetable,
								getfield: item.row.getfield,
								getid: item.row.getid
							}
						}));
						
					}
					else if  (data.total_rows == 0) {
						response($.map([{}], function(item) {
							return {
								// Message indicating nothing is found
								label: "No records found."
							}
						}))
					}
					else if  (data.total_rows == -1) {
						response($.map([{}], function(item) {
							return {
								// Message indicating no search performed
								label: "More information needed for search."
							}
						}))
					}
				}
			})
		},
		open: function() {
			// Highlight search text
			$(".ui-menu-item a").highlight( $("#searchinput").val() , "searchHighlight");
		},
		select: function(event, ui) {
			// Run function on selected record
			if (ui.item.responsetype) {
				locationFinder(ui.item.responsetype, ui.item.responsetable, ui.item.getfield, ui.item.getid, ui.item.label, ui.item.value);
			}
		}
	}).data("autocomplete")._renderMenu = function (ul, items) {
		var self = this,
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.responsetype != currentCategory && item.responsetype != undefined) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.responsetype + "</li>" );
					currentCategory = item.responsetype;
				}
				self._renderItem( ul, item );
			});
	};
	
	// select all when clicking on the search bar
    $("#searchinput").click(function() {
        $(this).select();
    });
	
	// autocomplete tips
	$("#searchdiv label span").click(function(){
		$('#search-dialog').dialog('open')
	});
});


/*  Document Load  */
$(window).load(function() {
   
   // Initialize Map
   initializeMap();
   
   // Process localstorage if available
   if (window.localStorage) {
		if (localStorage.getItem('gp_lastSelected')) locationFinder("Address", 'master_address_table', 'objectid', localStorage.getItem('gp_lastSelected'));
   }
   
   // Get GPS Location	   
   var gps = navigator.geolocation;
   if (gps) {
   		gps.getCurrentPosition(function(position) {
			// Check accuracy of GPS location
			if ( position.coords.accuracy < 100000 ) {
				// Make sure GPS location is within county extent
				if (position.coords.longitude > -81.0598 && position.coords.longitude < -80.54482 && position.coords.latitude > 35.00581 && position.coords.latitude < 35.5149) {
					$(".gpslocation").show();
					$("#gogpslocation").click(function() {
						addMarker(position.coords.longitude, position.coords.latitude, 1, "Estimated current position. <br />Accuracy: " + position.coords.accuracy + "m<br />Timestamp: " + position.timestamp);						
					});
				}
			}
		}, function() {}, {enableHighAccuracy:true});
   }
});


/*  Run Code When Active Accordion Tab Changes  */
function processAccordionDataChange(accordionValue) {
    if (null != selectedAddress) { // Make sure an address is selected
		switch (accordionValue) {
			
			case "SERVICES":
				if ($('#parks table tbody').html().length == 0) { // Make sure information isn't already popupated
					// Parks
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'parks', 'prkname as name,prkaddr as address,prktype,city, x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat', '', 50000, "", "5", 'json', '?');
					$.getJSON(url, function(data) {					  
						$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#parks table tbody");
					});
					// Get libraries
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'libraries', 'name,address,city, x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat', '', 100000, "", "5", 'json', '?');
					$.getJSON(url, function(data) {					  
						$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#libraries table tbody");
					});
					// Fire Stations
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'fire_stations', 'name,address,station_ty as type,x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat', '', 264000, "", "3", 'json', '?');
					$.getJSON(url, function(data) {					  
						$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#fire-stations table tbody");
					});
				}
				break;
			
			case "TRANSPORTATION":
				if ($('#bus-stops table tbody').html().length == 0) { // Make sure information isn't already popupated
					// CATS Bus Stops
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'busstops_pt', "stopdesc as name, routes as address,x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat", '', 10000, "", "10", 'json', '?');					
					$.getJSON(url, function(data) {					  
						$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#bus-stops table tbody");
					});
					// CATS Park and Ride Locations
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'cats_park_and_ride', 'name,routes,address,x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat', '', 100000, "", "3", 'json', '?');
					$.getJSON(url, function(data) {					  
							$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#park-and-rides table tbody");
					});
					// CATS Light Rail Stops
					url = pointBuffer(selectedAddress.x_coordinate, selectedAddress.y_coordinate, 2264, 'cats_light_rail_stations', "name,'' as address, x(transform(the_geom, 4326)) as lon, y(transform(the_geom, 4326)) as lat", '', 126400, "", "3", 'json', '?');
					$.getJSON(url, function(data) {					  
						$("#locate_template").tmpl(data.rows, { rowCount: data.total_rows }).appendTo("#light-rail-stops table tbody");					
					});
				}
				break;
		}
	}
}


